<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  

  
  <title>shiro与web集成 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="shiro提供了与web集成的支持，其通过一个ShiroFilter入口来拦截需要安全控制的URL,然后进行相应的控制，ShiroFilter类似于如Strut2/SpringMVC这种web框架的前端控制器，其实安全控制的入口点，其负责读取配置(如ini配置文件)，然后判断URL是否需要登录/权限等工作.">
<meta name="keywords" content="shiro">
<meta property="og:type" content="article">
<meta property="og:title" content="shiro与web集成">
<meta property="og:url" content="http://yoursite.com/2018/10/12/2018-03-14-shiro Web集成/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="shiro提供了与web集成的支持，其通过一个ShiroFilter入口来拦截需要安全控制的URL,然后进行相应的控制，ShiroFilter类似于如Strut2/SpringMVC这种web框架的前端控制器，其实安全控制的入口点，其负责读取配置(如ini配置文件)，然后判断URL是否需要登录/权限等工作.">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/13.png">
<meta property="og:updated_time" content="2018-11-01T14:24:04.931Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="shiro与web集成">
<meta name="twitter:description" content="shiro提供了与web集成的支持，其通过一个ShiroFilter入口来拦截需要安全控制的URL,然后进行相应的控制，ShiroFilter类似于如Strut2/SpringMVC这种web框架的前端控制器，其实安全控制的入口点，其负责读取配置(如ini配置文件)，然后判断URL是否需要登录/权限等工作.">
<meta name="twitter:image" content="http://p1aoqp63y.bkt.clouddn.com/13.png">
  
    <link rel="alternate" href="/org/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/org/css/style.css">
</head>
</html>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/org/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/org/">Home</a>
        
          <a class="main-nav-link" href="/org/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/org/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-2018-03-14-shiro Web集成" class="article article-type-post" itemscope="" itemprop="blogPost">
  <div class="article-meta">
    <a href="/org/2018/10/12/2018-03-14-shiro Web集成/" class="article-date">
  <time datetime="2018-10-12T09:03:30.000Z" itemprop="datePublished">2018-10-12</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      shiro与web集成
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>shiro提供了与web集成的支持，其通过一个ShiroFilter入口来拦截需要安全控制的URL,然后进行相应的控制，ShiroFilter类似于如Strut2/SpringMVC这种web框架的前端控制器，其实安全控制的入口点，其负责读取配置(如ini配置文件)，然后判断URL是否需要登录/权限等工作.</p>
<a id="more"></a>
<h3 id="准备环境"><a href="#准备环境" class="headerlink" title="准备环境"></a>准备环境</h3><p><strong>1、创建 webapp 应用</strong></p>
<p>此处我们使用了 jetty-maven-plugin 和 tomcat7-maven-plugin 插件；这样可以直接使用 “mvn jetty:run” 或“mvn tomcat7:run”直接运行 webapp 了。然后通过 URL<a href="http://localhost:8080/chapter7" target="_blank" rel="noopener">http://localhost:8080/chapter7</a> / 访问即可。</p>
<p><strong>2、依赖</strong></p>
<p>Servlet3</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;javax.servlet&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;3.0.1&lt;/version&gt;</span><br><span class="line">    &lt;scope&gt;provided&lt;/scope&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<p>Servlet3 的知识可以参考 <a href="https://github.com/zhangkaitao/servlet3-showcase" target="_blank" rel="noopener">https://github.com/zhangkaitao/servlet3-showcase</a> 及 Servlet3 规范 <a href="http://www.iteye.com/blogs/subjects/Servlet-3-1" target="_blank" rel="noopener">http://www.iteye.com/blogs/subjects/Servlet-3-1</a>。</p>
<p>shiro-web</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.apache.shiro&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;shiro-web&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.2.2&lt;/version&gt;</span><br><span class="line">&lt;/dependency</span><br></pre></td></tr></table></figure>
<h2 id="ShiroFilter-入口"><a href="#ShiroFilter-入口" class="headerlink" title="ShiroFilter 入口"></a>ShiroFilter 入口</h2><p><strong>1、Shiro 1.1 及以前版本配置方式</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;filter&gt;</span><br><span class="line">    &lt;filter-name&gt;iniShiroFilter&lt;/filter-name&gt;</span><br><span class="line">    &lt;filter-class&gt;org.apache.shiro.web.servlet.IniShiroFilter&lt;/filter-class&gt;</span><br><span class="line">    &lt;init-param&gt;</span><br><span class="line">        &lt;param-name&gt;configPath&lt;/param-name&gt;</span><br><span class="line">        &lt;param-value&gt;classpath:shiro.ini&lt;/param-value&gt;</span><br><span class="line">    &lt;/init-param&gt;</span><br><span class="line">&lt;/filter&gt;</span><br><span class="line">&lt;filter-mapping&gt;</span><br><span class="line">    &lt;filter-name&gt;iniShiroFilter&lt;/filter-name&gt;</span><br><span class="line">    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;</span><br><span class="line">&lt;/filter-mapping&gt;</span><br></pre></td></tr></table></figure>
<ol>
<li>使用 IniShiroFilter 作为 Shiro 安全控制的入口点，通过 url-pattern 指定需要安全的 URL；</li>
<li>通过 configPath 指定 ini 配置文件位置，默认是先从 /WEB-INF/shiro.ini 加载，如果没有就默认加载 classpath:shiro.ini，即默认相对于 web 应用上下文根路径；</li>
<li>也可以通过如下方式直接内嵌 ini 配置文件内容到 web.xml。</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;init-param&gt;</span><br><span class="line">    &lt;param-name&gt;config&lt;/param-name&gt;</span><br><span class="line">    &lt;param-value&gt;</span><br><span class="line">        ini配置文件贴在这</span><br><span class="line">    &lt;/param-value&gt;</span><br><span class="line">&lt;/init-param&gt;</span><br></pre></td></tr></table></figure>
<p><strong>2、Shiro 1.2 及以后版本的配置方式</strong></p>
<p>从 Shiro 1.2 开始引入了 Environment/WebEnvironment 的概念，即由它们的实现提供相应的 SecurityManager 及其相应的依赖。ShiroFilter 会自动找到 Environment 然后获取相应的依赖。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;listener&gt;</span><br><span class="line">   &lt;listener-class&gt;org.apache.shiro.web.env.EnvironmentLoaderListener&lt;/listener-class&gt;</span><br><span class="line">&lt;/listener&gt;</span><br></pre></td></tr></table></figure>
<p>通过 EnvironmentLoaderListener 来创建相应的 WebEnvironment，并自动绑定到 ServletContext，默认使用 IniWebEnvironment 实现。</p>
<p>可以通过如下配置修改默认实现及其加载的配置文件位置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;context-param&gt;</span><br><span class="line">   &lt;param-name&gt;shiroEnvironmentClass&lt;/param-name&gt;</span><br><span class="line">   &lt;param-value&gt;org.apache.shiro.web.env.IniWebEnvironment&lt;/param-value&gt;</span><br><span class="line">&lt;/context-param&gt;</span><br><span class="line">    &lt;context-param&gt;</span><br><span class="line">        &lt;param-name&gt;shiroConfigLocations&lt;/param-name&gt;</span><br><span class="line">        &lt;param-value&gt;classpath:shiro.ini&lt;/param-value&gt;</span><br><span class="line">    &lt;/context-param&gt;</span><br></pre></td></tr></table></figure>
<p>shiroConfigLocations 默认是 “/WEB-INF/shiro.ini”，IniWebEnvironment 默认是先从 / WEB-INF/shiro.ini 加载，如果没有就默认加载 classpath:shiro.ini</p>
<p><strong>3、与 Spring 集成</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;filter&gt;</span><br><span class="line">    &lt;filter-name&gt;shiroFilter&lt;/filter-name&gt;</span><br><span class="line">    &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;</span><br><span class="line">    &lt;init-param&gt;</span><br><span class="line">        &lt;param-name&gt;targetFilterLifecycle&lt;/param-name&gt;</span><br><span class="line">        &lt;param-value&gt;true&lt;/param-value&gt;</span><br><span class="line">    &lt;/init-param&gt;</span><br><span class="line">&lt;/filter&gt;</span><br><span class="line">&lt;filter-mapping&gt;</span><br><span class="line">    &lt;filter-name&gt;shiroFilter&lt;/filter-name&gt;</span><br><span class="line">    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;</span><br><span class="line">&lt;/filter-mapping&gt;</span><br></pre></td></tr></table></figure>
<p>DelegatingFilterProxy 作用是自动到 spring 容器查找名字为 shiroFilter（filter-name）的 bean 并把所有 Filter 的操作委托给它。然后将 ShiroFilter 配置到 spring 容器即可：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=&quot;shiroFilter&quot; class=&quot;org.apache.shiro.spring.web.ShiroFilterFactoryBean&quot;&gt;</span><br><span class="line">&lt;property name=&quot;securityManager&quot; ref=&quot;securityManager&quot;/&gt;</span><br><span class="line">&lt;!—忽略其他，详见与Spring集成部分 --&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<p>最后不要忘了使用 org.springframework.web.context.ContextLoaderListener 加载这个 spring 配置文件即可。因为我们现在的 shiro 版本是 1.2 的，因此之后的测试都是使用 1.2 的配置</p>
<h2 id="Web-INI-配置"><a href="#Web-INI-配置" class="headerlink" title="Web INI 配置"></a>Web INI 配置</h2><p>ini 配置部分和之前的相比将多出对 url 部分的配置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">[main]</span><br><span class="line">\#默认是/login.jsp</span><br><span class="line">authc.loginUrl=/login</span><br><span class="line">roles.unauthorizedUrl=/unauthorized</span><br><span class="line">perms.unauthorizedUrl=/unauthorized</span><br><span class="line">[users]</span><br><span class="line">zhang=123,admin</span><br><span class="line">wang=123</span><br><span class="line">[roles]</span><br><span class="line">admin=user:*,menu:*</span><br><span class="line">[urls]</span><br><span class="line">/login=anon</span><br><span class="line">/unauthorized=anon</span><br><span class="line">/static/**=anon</span><br><span class="line">/authenticated=authc</span><br><span class="line">/role=authc,roles[admin]</span><br><span class="line">/permission=authc,perms[&quot;user:create&quot;]</span><br></pre></td></tr></table></figure>
<p>其中最重要的就是 [urls] 部分的配置，其格式是： “url = 拦截器 [参数]，拦截器[参数]”；即如果当前请求的 url 匹配[urls] 部分的某个 url 模式，将会执行其配置的拦截器。比如 anon 拦截器表示匿名访问（即不需要登录即可访问）；authc 拦截器表示需要身份认证通过后才能访问；roles[admin]拦截器表示需要有 admin 角色授权才能访问；而 perms[“user:create”]拦截器表示需要有 “user:create” 权限才能访问。</p>
<p><strong>url 模式使用 Ant 风格模式</strong><br>Ant 路径通配符支持?、、<strong>，注意通配符匹配不包括目录分隔符 “/”：</strong>?：匹配一个字符<strong>，如”/admin?” 将匹配 / admin1，但不匹配 / admin 或 / admin2；</strong>\：匹配零个或多个字符串<strong>，如 / admin * 将匹配 / admin、/admin123，但不匹配 / admin/1；</strong>\：匹配路径中的零个或多个路径<strong>，如 / admin/</strong> 将匹配 / admin/a 或 / admin/a/b。</p>
<p><strong>url 模式匹配顺序</strong></p>
<p>url 模式匹配顺序是按照在配置中的声明顺序匹配，即从头开始使用第一个匹配的 url 模式对应的拦截器链。如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">/bb/**=filter1</span><br><span class="line">/bb/aa=filter2</span><br><span class="line">/**=filter3</span><br></pre></td></tr></table></figure>
<p>如果请求的 url 是 “/bb/aa”，因为按照声明顺序进行匹配，那么将使用 filter1 进行拦截。</p>
<p>拦截器将在下一节详细介绍。接着我们来看看身份验证、授权及退出在 web 中如何实现。</p>
<h3 id="身份验证（登录）"><a href="#身份验证（登录）" class="headerlink" title="身份验证（登录）"></a>身份验证（登录）</h3><p><strong>首先配置需要身份验证的 url</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">/authenticated=authc</span><br><span class="line">/role=authc,roles[admin]</span><br><span class="line">/permission=authc,perms[&quot;user:create&quot;]</span><br></pre></td></tr></table></figure>
<p>即访问这些地址时会首先判断用户有没有登录，如果没有登录默会跳转到登录页面，默认是 / login.jsp，可以通过在 [main] 部分通过如下配置修改：</p>
<p><code>authc.loginUrl=/login</code></p>
<p><strong>登录 Servlet（com.github.zhangkaitao.shiro.chapter7.web.servlet.LoginServlet）</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(name = &quot;loginServlet&quot;, urlPatterns = &quot;/login&quot;)</span><br><span class="line">public class LoginServlet extends HttpServlet &#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp)</span><br><span class="line">      throws ServletException, IOException &#123;</span><br><span class="line">        req.getRequestDispatcher(&quot;/WEB-INF/jsp/login.jsp&quot;).forward(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doPost(HttpServletRequest req, HttpServletResponse resp)</span><br><span class="line">      throws ServletException, IOException &#123;</span><br><span class="line">        String error = null;</span><br><span class="line">        String username = req.getParameter(&quot;username&quot;);</span><br><span class="line">        String password = req.getParameter(&quot;password&quot;);</span><br><span class="line">        Subject subject = SecurityUtils.getSubject();</span><br><span class="line">        UsernamePasswordToken token = new UsernamePasswordToken(username, password);</span><br><span class="line">        try &#123;</span><br><span class="line">            subject.login(token);</span><br><span class="line">        &#125; catch (UnknownAccountException e) &#123;</span><br><span class="line">            error = &quot;用户名/密码错误&quot;;</span><br><span class="line">        &#125; catch (IncorrectCredentialsException e) &#123;</span><br><span class="line">            error = &quot;用户名/密码错误&quot;;</span><br><span class="line">        &#125; catch (AuthenticationException e) &#123;</span><br><span class="line">            //其他错误，比如锁定，如果想单独处理请单独catch处理</span><br><span class="line">            error = &quot;其他错误：&quot; + e.getMessage();</span><br><span class="line">        &#125;</span><br><span class="line">        if(error != null) &#123;//出错了，返回登录页面</span><br><span class="line">            req.setAttribute(&quot;error&quot;, error);</span><br><span class="line">            req.getRequestDispatcher(&quot;/WEB-INF/jsp/login.jsp&quot;).forward(req, resp);</span><br><span class="line">        &#125; else &#123;//登录成功</span><br><span class="line">            req.getRequestDispatcher(&quot;/WEB-INF/jsp/loginSuccess.jsp&quot;).forward(req, resp);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;&amp;nbsp;</span><br></pre></td></tr></table></figure>
<ol>
<li><p>doGet 请求时展示登录页面；</p>
</li>
<li><p>doPost 时进行登录，登录时收集 username/password 参数，然后提交给 Subject 进行登录。如果有错误再返回到登录页面；否则跳转到登录成功页面（此处应该返回到访问登录页面之前的那个页面，或者没有上一个页面时访问主页）。</p>
</li>
<li><p>JSP 页面请参考源码。</p>
<p><strong>测试</strong></p>
<p>首先输入 <a href="http://localhost:8080/chapter7/login" target="_blank" rel="noopener">http://localhost:8080/chapter7/login</a> 进行登录，登录成功后接着可以访问 <a href="http://localhost:8080/chapter7/authenticated" target="_blank" rel="noopener">http://localhost:8080/chapter7/authenticated</a> 来显示当前登录的用户：</p>
<p><code>${subject.principal} 身份验证已通过。</code></p>
<p>当前实现的一个缺点就是，永远返回到同一个成功页面（比如首页），在实际项目中比如支付时如果没有登录将跳转到登录页面，登录成功后再跳回到支付页面；对于这种功能大家可以在登录时把当前请求保存下来，然后登录成功后再重定向到该请求即可。</p>
<p>Shiro 内置了登录（身份验证）的实现：基于表单的和基于 Basic 的验证，其通过拦截器实现。</p>
<h3 id="基于-Basic-的拦截器身份验证"><a href="#基于-Basic-的拦截器身份验证" class="headerlink" title="基于 Basic 的拦截器身份验证"></a>基于 Basic 的拦截器身份验证</h3><p><strong>shiro-basicfilterlogin.ini 配置</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[main]</span><br><span class="line">authcBasic.applicationName=please login</span><br><span class="line">………省略users</span><br><span class="line">[urls]</span><br><span class="line">/role=authcBasic,roles[admin]&amp;nbsp;</span><br></pre></td></tr></table></figure>
<p>1、authcBasic 是 org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter 类型的实例，其用于实现基于 Basic 的身份验证；applicationName 用于弹出的登录框显示信息使用，如图：</p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/13.png" alt="2"></p>
<p>2、[urls] 部分配置了 /role 地址需要走 authcBasic 拦截器，即如果访问 /role 时还没有通过身份验证那么将弹出如上图的对话框进行登录，登录成功即可访问。</p>
<p><strong>web.xml</strong></p>
<p>把 shiroConfigLocations 改为 shiro-basicfilterlogin.ini 即可。</p>
<p><strong>测试</strong></p>
<p>输入 <a href="http://localhost:8080/chapter7/role%EF%BC%8C%E4%BC%9A%E5%BC%B9%E5%87%BA%E4%B9%8B%E5%89%8D%E7%9A%84" target="_blank" rel="noopener">http://localhost:8080/chapter7/role</a>，会弹出之前的 Basic 验证对话框输入 “zhang/123” 即可登录成功进行访问。</p>
</li>
</ol>
<h3 id="基于表单的拦截器身份验证"><a href="#基于表单的拦截器身份验证" class="headerlink" title="基于表单的拦截器身份验证"></a>基于表单的拦截器身份验证</h3><p>基于表单的拦截器身份验证和【1】类似，但是更简单，因为其已经实现了大部分登录逻辑；我们只需要指定：登录地址 / 登录失败后错误信息存哪 / 成功的地址即可。</p>
<p><strong>shiro-formfilterlogin.ini</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">[main]</span><br><span class="line">authc.loginUrl=/formfilterlogin</span><br><span class="line">authc.usernameParam=username</span><br><span class="line">authc.passwordParam=password</span><br><span class="line">authc.successUrl=/</span><br><span class="line">authc.failureKeyAttribute=shiroLoginFailure</span><br><span class="line">[urls]</span><br><span class="line">/role=authc,roles[admin]&amp;nbsp;</span><br></pre></td></tr></table></figure>
<p>1、authc 是 org.apache.shiro.web.filter.authc.FormAuthenticationFilter 类型的实例，其用于实现基于表单的身份验证；通过 loginUrl 指定当身份验证时的登录表单；usernameParam 指定登录表单提交的用户名参数名；passwordParam 指定登录表单提交的密码参数名；successUrl 指定登录成功后重定向的默认地址（默认是 “/”）（如果有上一个地址会自动重定向带该地址）；failureKeyAttribute 指定登录失败时的 request 属性 key（默认 shiroLoginFailure）；这样可以在登录表单得到该错误 key 显示相应的错误消息；</p>
<p><strong>web.xml</strong></p>
<p>把 shiroConfigLocations 改为 shiro-formfilterlogin.ini 即可。</p>
<p><strong>登录 Servlet</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(name = &quot;formFilterLoginServlet&quot;, urlPatterns = &quot;/formfilterlogin&quot;)</span><br><span class="line">public class FormFilterLoginServlet extends HttpServlet &#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp)</span><br><span class="line">      throws ServletException, IOException &#123;</span><br><span class="line">        doPost(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doPost(HttpServletRequest req, HttpServletResponse resp)</span><br><span class="line">     throws ServletException, IOException &#123;</span><br><span class="line">        String errorClassName = (String)req.getAttribute(&quot;shiroLoginFailure&quot;);</span><br><span class="line">        if(UnknownAccountException.class.getName().equals(errorClassName)) &#123;</span><br><span class="line">            req.setAttribute(&quot;error&quot;, &quot;用户名/密码错误&quot;);</span><br><span class="line">        &#125; else if(IncorrectCredentialsException.class.getName().equals(errorClassName)) &#123;</span><br><span class="line">            req.setAttribute(&quot;error&quot;, &quot;用户名/密码错误&quot;);</span><br><span class="line">        &#125; else if(errorClassName != null) &#123;</span><br><span class="line">            req.setAttribute(&quot;error&quot;, &quot;未知错误：&quot; + errorClassName);</span><br><span class="line">        &#125;</span><br><span class="line">        req.getRequestDispatcher(&quot;/WEB-INF/jsp/formfilterlogin.jsp&quot;).forward(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在登录 Servlet 中通过 shiroLoginFailure 得到 authc 登录失败时的异常类型名，然后根据此异常名来决定显示什么错误消息。</p>
<p><strong>测试</strong></p>
<p>输入 <code>http://localhost:8080/chapter7/role</code>，会跳转到 “/formfilterlogin” 登录表单，提交表单如果 authc 拦截器登录成功后，会直接重定向会之前的地址 “/role”；假设我们直接访问 “/formfilterlogin” 的话登录成功将直接到默认的 successUrl。</p>
<h3 id="授权（角色-权限验证）"><a href="#授权（角色-权限验证）" class="headerlink" title="授权（角色 / 权限验证）"></a>授权（角色 / 权限验证）</h3><p><strong>shiro.ini</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[main]</span><br><span class="line">roles.unauthorizedUrl=/unauthorized</span><br><span class="line">perms.unauthorizedUrl=/unauthorized</span><br><span class="line"> [urls]</span><br><span class="line">/role=authc,roles[admin]</span><br><span class="line">/permission=authc,perms[&quot;user:create&quot;]</span><br></pre></td></tr></table></figure>
<p>通过 unauthorizedUrl 属性指定如果授权失败时重定向到的地址。roles 是 org.apache.shiro.web.filter.authz.RolesAuthorizationFilter 类型的实例，通过参数指定访问时需要的角色，如 “[admin]”，如果有多个使用 “，” 分割，且验证时是 hasAllRole 验证，即且的关系。Perms 是 org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter 类型的实例，和 roles 类似，只是验证权限字符串。</p>
<p><strong>web.xml</strong></p>
<p>把 shiroConfigLocations 改为 shiro.ini 即可。</p>
<p><strong>RoleServlet/PermissionServlet</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(name = &quot;permissionServlet&quot;, urlPatterns = &quot;/permission&quot;)</span><br><span class="line">public class PermissionServlet extends HttpServlet &#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp)</span><br><span class="line">      throws ServletException, IOException &#123;</span><br><span class="line">        Subject subject = SecurityUtils.getSubject();</span><br><span class="line">        subject.checkPermission(&quot;user:create&quot;);</span><br><span class="line">        req.getRequestDispatcher(&quot;/WEB-INF/jsp/hasPermission.jsp&quot;).forward(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(name = &quot;roleServlet&quot;, urlPatterns = &quot;/role&quot;)</span><br><span class="line">public class RoleServlet extends HttpServlet &#123;</span><br><span class="line">    @Override</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp)</span><br><span class="line">      throws ServletException, IOException &#123;</span><br><span class="line">        Subject subject = SecurityUtils.getSubject();</span><br><span class="line">        subject.checkRole(&quot;admin&quot;);</span><br><span class="line">        req.getRequestDispatcher(&quot;/WEB-INF/jsp/hasRole.jsp&quot;).forward(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;&amp;nbsp;</span><br></pre></td></tr></table></figure>
<h3 id="退出"><a href="#退出" class="headerlink" title="退出"></a>退出</h3><p><strong>shiro.ini</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[urls]</span><br><span class="line">/logout=anon&amp;nbsp;</span><br></pre></td></tr></table></figure>
<p>指定 /logout 使用 anon 拦截器即可，即不需要登录即可访问。</p>
<p><strong>LogoutServlet</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet(name = &quot;logoutServlet&quot;, urlPatterns = &quot;/logout&quot;)</span><br><span class="line">public class LogoutServlet extends HttpServlet &#123;</span><br><span class="line">    protected void doGet(HttpServletRequest req, HttpServletResponse resp)</span><br><span class="line">      throws ServletException, IOException &#123;</span><br><span class="line">        SecurityUtils.getSubject().logout();</span><br><span class="line">        req.getRequestDispatcher(&quot;/WEB-INF/jsp/logoutSuccess.jsp&quot;).forward(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;&amp;nbsp;</span><br></pre></td></tr></table></figure>
<p>直接调用 Subject.logout 即可，退出成功后转发 / 重定向到相应页面即可。</p>
<p><strong>测试</strong></p>
<p>首先访问 <code>http://localhost:8080/chapter7/login</code>，使用帐号 “zhang/123” 进行登录，登录成功后访问 /logout 即可退出。</p>
<p>Shiro 也提供了 logout 拦截器用于退出，其是 org.apache.shiro.web.filter.authc.LogoutFilter 类型的实例，我们可以在 shiro.ini 配置文件中通过如下配置完成退出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">[main]</span><br><span class="line"></span><br><span class="line">logout.redirectUrl=/login</span><br><span class="line"></span><br><span class="line">[urls]</span><br><span class="line"></span><br><span class="line">/logout2=logout</span><br></pre></td></tr></table></figure>
<p>&nbsp;</p>
<p>通过 logout.redirectUrl 指定退出后重定向的地址；通过 /logout2=logout 指定退出 url 是 /logout2。这样当我们登录成功后然后访问 /logout2 即可退出。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2018/10/12/2018-03-14-shiro Web集成/" data-id="cjoztxu2r000p1wij8h4ywxns" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/org/tags/shiro/">shiro</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/org/2018/10/12/2018-02-27-Spring MVC文件上传处理/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          springMVC的文件上传
        
      </div>
    </a>
  
  
    <a href="/org/2018/10/12/2018-03-15-shiro拦截器/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">shiro拦截器机制</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/SVN/">SVN</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/Spring-secrity/">Spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hexo/">hexo</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hibenrate/">hibenrate</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jekyll/">jekyll</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jenkins/">jenkins</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/redis/">redis</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/shiro/">shiro</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spingMVC/">spingMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring-cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-secrity/">spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springMVC/">springMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springboot/">springboot</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/生活/">生活</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/org/tags/SVN/" style="font-size: 12px;">SVN</a> <a href="/org/tags/Spring-secrity/" style="font-size: 10px;">Spring-secrity</a> <a href="/org/tags/hexo/" style="font-size: 10px;">hexo</a> <a href="/org/tags/hibenrate/" style="font-size: 10px;">hibenrate</a> <a href="/org/tags/jekyll/" style="font-size: 10px;">jekyll</a> <a href="/org/tags/jenkins/" style="font-size: 10px;">jenkins</a> <a href="/org/tags/redis/" style="font-size: 16px;">redis</a> <a href="/org/tags/shiro/" style="font-size: 18px;">shiro</a> <a href="/org/tags/spingMVC/" style="font-size: 10px;">spingMVC</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring cloud</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring-cloud</a> <a href="/org/tags/spring-secrity/" style="font-size: 12px;">spring-secrity</a> <a href="/org/tags/springMVC/" style="font-size: 14px;">springMVC</a> <a href="/org/tags/springboot/" style="font-size: 20px;">springboot</a> <a href="/org/tags/生活/" style="font-size: 10px;">生活</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/11/">November 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/10/">October 2018</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/org/2018/11/27/redis07-zookeeper-kafka集群部署以及如何使用简单介绍/">redis07-zookeeper+kafka集群部署以及如何使用简单介绍</a>
          </li>
        
          <li>
            <a href="/org/2018/11/13/redis06-cluster实现高可用性/">redis06-cluster实现高可用性</a>
          </li>
        
          <li>
            <a href="/org/2018/11/12/redis05-在项目中搭建读写分-高可用-多master的redis-cluster集群/">redis05-在项目中搭建读写分+高可用+多master的redis cluster集群</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/在项目中用经典的三节点方式部署哨兵集群-笔记/">在项目中用经典的三节点方式部署哨兵集群-笔记</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/redis哨兵的多个核心底层原理-笔记/">redis哨兵的多个核心底层原理-笔记</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/org/" class="mobile-nav-link">Home</a>
  
    <a href="/org/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>


  <link rel="stylesheet" href="/org/fancybox/jquery.fancybox.css">
  <script src="/org/fancybox/jquery.fancybox.pack.js"></script>


<script src="/org/js/script.js"></script>



  </div>
</body>
</html>